﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Collections;
using System.Windows.Threading;

namespace XWord.WPF.Behaviors
{
    public class TextBoxForListBoxSearchBehavior : Behavior<TextBox>
    {
        protected override void OnAttached()
        {
            this.AssociatedObject.SelectionChanged += new RoutedEventHandler(AssociatedObject_SelectionChanged);
            base.OnAttached();
        }

        private List<object> searchList;

        void AssociatedObject_SelectionChanged(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (string.IsNullOrEmpty(tb.Text.Trim())) return;
            if (searchList == null)
            {
                var list = ListBoxElement.ItemsSource as IList;
                if (list == null) return;
                searchList = list.Cast<object>().ToList();
            }
            var t = searchList.Find(o => o.GetType().GetProperty(SearchName).GetValue(o, null).ToString().IndexOf(tb.Text) != -1);
            if (t != null)
            {
                Dispatcher.BeginInvoke(DispatcherPriority.Render, new Action(() =>
                {

                    {
                        ListBoxElement.ScrollIntoView(t);
                    }
                }));
            }
        }
        
        public string SearchName { get; set; }

        public ListBox ListBoxElement
        {
            get { return (ListBox)GetValue(ListBoxElementProperty); }
            set { SetValue(ListBoxElementProperty, value); }
        }

        public static readonly DependencyProperty ListBoxElementProperty =
            DependencyProperty.Register("ListBoxElement", typeof(ListBox), typeof(TextBoxForListBoxSearchBehavior), 
            new UIPropertyMetadata(null));

    }
}
